package com.heima.app.gateway.filter;

import com.heima.app.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 定义全局过滤器
 */
@Configuration
@Order(1)
public class AuthorizeFilter implements GlobalFilter {
    /**
     * 实现用户登录鉴权
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 1.判断是否是登录的请求
        String path = request.getURI().getPath();
        if (path.contains("/login/login_aut")) {
            // 是。直接放行
            return chain.filter(exchange);
        }
        // 否。判断是否有token
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isEmpty(token)) {
            // 否。拦截并返回错误代码和提示
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // 是。判断token是否过期
        Claims claims = AppJwtUtil.getClaimsBody(token);
        int time = AppJwtUtil.verifyToken(claims);
        if (time == 1 || time == 2) {
            // 过期。拦截并返回错误代码和提示
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // 没过期。放行
        return chain.filter(exchange);
    }
}
